'use strict';
const { ORG_MAP, INDUSTRY_MAP } = require('../dict');

const Service = require('egg').Service;

class MediaService extends Service {
  async getList({ mediaName, mediaState, orgId, pageNum = 1, pageSize = 20 }) {
    const { Op } = this.app.Sequelize;
    const where = {};
    if (mediaName) {
      where.mediaName = {
        [Op.like]: `%${mediaName}%`,
      };
    }
    if (mediaState) {
      where.mediaState = mediaState;
    }
    if (orgId) {
      where.orgId = orgId;
    }
    const users = await this.ctx.model.Media.findAndCountAll({
      where,
      offset: (pageNum - 1) * pageSize,
      limit: Number(pageSize),
      order: [
        [ 'id', 'DESC' ],
      ],
    });
    const rows = users.rows.map(item => {
      const values = { ...item.dataValues };
      const { orgId, industryCode, receivers } = values;
      values.orgName = ORG_MAP[orgId];
      values.industryName = INDUSTRY_MAP[industryCode];
      values.receivers = receivers ? JSON.parse(receivers) : [];
      return values;
    });
    return { ...users, rows };
  }

  async getDetail(mediaId) {
    const media = await this.ctx.model.Media.findOne({
      where: {
        mediaId,
      },
    });
    return media;
  }

  async create(mediaInfo) {
    const user = await this.ctx.model.Media.create(mediaInfo);
    return user;
  }

  async update({ mediaId, mediaName, appName, appPackage, appStoreUrl, domain, miniappId, miniappName, mediaState }) {
    const updateRes = await this.ctx.model.Media.update(
      {
        mediaName, appName, appPackage, appStoreUrl, domain, miniappId, miniappName, mediaState,
      },
      {
        where: {
          mediaId,
        },
      }
    );
    return updateRes && updateRes[0] > 0;
  }

  async addReceiver({ mediaId, receiverId, outMediaId }) {
    const media = await this.ctx.model.Media.findOne({
      where: {
        mediaId,
      },
    });
    if (!media) return;
    const { receivers } = media;
    const arr = receivers ? JSON.parse(receivers) : [];
    arr.push({
      receiverId,
      outMediaId,
    });
    const updateRes = await this.ctx.model.Media.update({
      receivers: JSON.stringify(arr),
    }, {
      where: {
        mediaId,
      },
    });
    return updateRes && updateRes[0] > 0;
  }

  async updateReceiver({ mediaId, receiverList }) {
    const updateRes = await this.ctx.model.Media.update({
      receivers: JSON.stringify(receiverList),
    }, {
      where: {
        mediaId,
      },
    });
    return updateRes && updateRes[0] > 0;
  }

}

module.exports = MediaService;
